package com.zhang.interceptors;

import com.zhang.pojo.Result;
import com.zhang.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component //注入到IOC容器当中
public class LoginInterceptor implements HandlerInterceptor {

    //重写preHandler方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截逻辑

        //从请求头Authorization中获取token
        String token = request.getHeader("Authorization");

        //验证token,并接受载荷中的业务数据id、username
        //try：验证通过 catch：验证失败  （Ctrl+Alt+T 快速生成try catch）
        try {
            Map<String, Object> clamis = JwtUtil.parseToken(token);
            //放行
            return true;
        } catch (Exception e) {
            //将响应状态码改为401，标识失败
            response.setStatus(401);
            //不放行
            return false;
        }
    }
}
